package com.lyhengtongwl.zqsnews.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnHighlightDrewListener;
import com.app.hubert.guide.listener.OnLayoutInflatedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.app.hubert.guide.model.HighlightOptions;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseFragment;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.net.UpClickCount;
import com.lyhengtongwl.zqsnews.ui.activity.MainActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsDDListActivityNew;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebGLActivity;
import com.lyhengtongwl.zqsnews.ui.activity.QCInvitationActivity;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.FTYUtils;
import com.lyhengtongwl.zqsnews.utils.ImgHelper;
import com.lyhengtongwl.zqsnews.utils.NewsOpenShare;
import com.lyhengtongwl.zqsnews.utils.PermissionUtils;
import com.lyhengtongwl.zqsnews.utils.PhoneUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.widget.NewsShare;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

import static android.support.v4.content.PermissionChecker.PERMISSION_GRANTED;

public class NewsMMByEnlightenFragment extends BaseFragment {
    @BindView(R.id.tv_title)
    TextView tv_count;//徒弟总数
    @BindView(R.id.tv_money)
    TextView tv_money;//累计收益(总的收益)
    @BindView(R.id.tv_today)
    TextView tv_today;//今日收益
    @BindView(R.id.tv_yesterday)
    TextView tv_yesterday;//昨日收益
    @BindView(R.id.validCount)
    TextView tv_validCount;//有效徒弟数
    @BindView(R.id.discipleCount)
    TextView tv_discipleCount;//有效徒孙数

    @BindView(R.id.prenticeShare)
    TextView tv_prenticeShare;//徒弟贡献
    @BindView(R.id.discipleShare)
    TextView tv_discipleShare;//徒孙贡献
    private View view1;
    private ImageView imageView;
    private boolean isFirst = true;

    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_newsenlighten, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //修改页面上view的属性等
    }

    @OnClick({R.id.ll_QrCodeInvitation, R.id.ll_wcInvitation,
            R.id.ll_wccInvitation, R.id.ll_gl,
            R.id.iv_EnlighteningStrategy,
            R.id.tv_share, R.id.ll_1, R.id.ll_2, R.id.ll_3, R.id.ll_4, R.id.tv_phone,R.id.btn_screen})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }

        switch (view.getId()) {
            case R.id.ll_QrCodeInvitation://二维码邀请
                startActivity(new Intent(getActivity(), QCInvitationActivity.class));
                break;
            case R.id.ll_wcInvitation://微信邀请
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (list != null && list.size() > 0){
//                            Bitmap bitmapFormResources = ImgHelper.getBitmapFormResources(getActivity(), R.mipmap.red_packet);
//                            NewsShareUtils.shareUrlToFriends(getActivity(), "欢迎来到赚钱树"
//                                    , Url.H5BaseUrl + "/ht/webLogin.html?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), bitmapFormResources);
//                    }}
//                }).start();

                new NewsOpenShare(getActivity()).ShareUrlToWx(Constant.ShareDetail, AppConfig.getInstance(App.getContext()).get("redBagUrl") + "?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), R.mipmap.red_packet, AppConfig.getInstance(App.getContext()).get("redBagUrl"), 0);
                break;
            case R.id.ll_wccInvitation://朋友圈邀请
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (list != null && list.size() > 0) {
//                            Bitmap bitmapFormResources = ImgHelper.getBitmapFormResources(getActivity(), R.mipmap.red_packet);
//                            NewsShareUtils.shareUrlToCircleFriends(getActivity(), "欢迎来到赚钱树"
//                                    , Url.H5BaseUrl + "/ht/webLogin.html?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), bitmapFormResources);
//                        }
//                    }
//                }).start();
                new NewsOpenShare(getActivity()).ShareUrlToWx(Constant.ShareDetail, AppConfig.getInstance(App.getContext()).get("redBagUrl") + "?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), R.mipmap.red_packet, AppConfig.getInstance(App.getContext()).get("redBagUrl"), 1);
                break;
            case R.id.ll_gl://收徒攻略
            case R.id.iv_EnlighteningStrategy:
                UpClickCount.getInstance(getActivity()).upClick("strategy", "攻略");
                startActivity(new Intent(getActivity(), NewsWebGLActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("strategyUrl")).putExtra("isDefault", "false")
                );
                break;
            case R.id.tv_share://立即收徒
                NewsShare.showShareDialog_1(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), getActivity());
                break;

            case R.id.ll_1:
            case R.id.ll_2://有效徒弟列表
                startActivity(new Intent(getActivity(), NewsDDListActivityNew.class).putExtra("type", "0"));
                break;
            case R.id.ll_3:
            case R.id.ll_4://有效徒孙列表
                startActivity(new Intent(getActivity(), NewsDDListActivityNew.class).putExtra("type", "1"));
                break;
            case R.id.tv_phone://跳转系统通讯录
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED) {
                    PermissionUtils.getInstance().showSystemPermissionsSettingDialog1(getActivity());
                } else {
                    new PhoneUtils(getActivity()).upLoadPhones();
//                    Intent intent001 = new Intent();
//                    intent001.setClassName("com.android.contacts", "com.android.contacts.activities.PeopleActivity");
//                    startActivity(intent001);
                    Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, 33);
                }
                break;
            case R.id.btn_screen://测试穿山甲的全屏视频
//                startActivity(new Intent(getActivity(), CSJFullScreenActivity.class));
                break;

        }
    }


    /**
     * 获取通讯录权限
     */
    private void getReadPhonePermission() {
        int flag = ActivityCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.READ_CONTACTS);
        if (flag != PackageManager.PERMISSION_GRANTED) {
            NewsMMByEnlightenFragment.this.requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 2);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PERMISSION_GRANTED) {//选择了“始终允许”
//                    获取通讯录并上传  跳转通讯录
                    new PhoneUtils(getActivity()).upLoadPhones();
                } else {//权限被拒绝
                }
            }
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirst) {
                isFirst = false;
                getReadPhonePermission();
            }

            getAllInCome();
            String isFirst = SPUtils.get(App.getContext(), "isFirst", "true") + "";

            if (("true").equals(isFirst)) {
                SPUtils.put(App.getContext(), "isFirst", "false");
                view1 = ((MainActivity) getActivity()).getTabLayout(1).getIconView(1);
                setNewsGuide();
            }
        }
    }

    //获取数据信息
    private void getAllInCome() {
        Task.getApiService().getAllInCome().enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    String prenticeCount = jsonObject.getInteger("prenticeCount") + "";//徒弟总数
                    String allIncome = jsonObject.getInteger("allIncome") + "";//总的收益
                    String yesterdayIncome = jsonObject.getInteger("yesterdayIncome") + "";//昨日收益
                    String todayIncome = jsonObject.getInteger("todayIncome") + "";//今日收益
                    String validCount = jsonObject.getInteger("validCount") + "";//有效徒弟数
                    String discipleCount = jsonObject.getInteger("discipleCount") + "";//有效徒孙数据
                    String prenticeShare = jsonObject.getInteger("prenticeShare") + "";//徒弟贡献
                    String discipleShare = jsonObject.getInteger("discipleShare") + "";//徒孙贡献
//                    tv_count.setText(prenticeCount+"位徒弟共计帮您赚了(元)");
                    tv_money.setText(FTYUtils.fenToYuan(allIncome));
                    tv_today.setText(FTYUtils.fenToYuan(todayIncome));
                    tv_yesterday.setText(FTYUtils.fenToYuan(yesterdayIncome));
                    tv_validCount.setText(prenticeCount);
                    tv_discipleCount.setText(discipleCount);
                    tv_prenticeShare.setText(FTYUtils.fenToYuan(prenticeShare));
                    tv_discipleShare.setText(FTYUtils.fenToYuan(discipleShare));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    private void setNewsGuide() {
        HighlightOptions options = new HighlightOptions.Builder()
                .setOnHighlightDrewListener(new OnHighlightDrewListener() {
                    @SuppressLint("NewApi")
                    @Override
                    public void onHighlightDrew(Canvas canvas, RectF rectF) {
                        Paint paint = new Paint();
                        paint.setColor(Color.WHITE);
                        paint.setStyle(Paint.Style.STROKE);
                        paint.setStrokeWidth(2);
                        paint.setPathEffect(new DashPathEffect(new float[]{10, 10}, 0));
                        Matrix m = new Matrix();
                        m.setRotate(0);
                        m.setTranslate(0, 0);
                        Bitmap bitmapFormResources = ImgHelper.getBitmapFormResources(getActivity(), R.drawable.img_circle);
                        float imgX = (bitmapFormResources.getWidth() - rectF.width()) / 2;
                        float imgY = (bitmapFormResources.getHeight() - rectF.height()) / 2;
                        float hightLightX = rectF.centerX() - rectF.width() - imgX / 2;
                        float hightLightY = rectF.centerY() - rectF.height() + imgY / 2;
                        canvas.drawBitmap(bitmapFormResources, hightLightX, hightLightY, paint);

                        Bitmap bitmapFormResources1 = ImgHelper.getBitmapFormResources(getActivity(), R.drawable.img_word);
                        float hightLightX1 = rectF.centerX() - imgX * 2 - rectF.width() / 2;
                        float hightLightY1 = rectF.centerY() - rectF.height() - bitmapFormResources.getHeight();
                        canvas.drawBitmap(bitmapFormResources1, hightLightX1, hightLightY1, paint);

                        Bitmap bitmapFormResources2 = ImgHelper.getBitmapFormResources(getActivity(), R.drawable.icon_recruit_selected);

                        float imgX2 = (bitmapFormResources2.getWidth() - rectF.width()) / 2;
                        float imgY2 = (bitmapFormResources2.getHeight() - rectF.height()) / 2;
                        float hightLightX2 = rectF.centerX() - rectF.width() / 2 - imgX2;
                        float hightLightY2 = rectF.centerY() - rectF.height() / 2 - imgY2;
                        canvas.drawBitmap(bitmapFormResources2, hightLightX2, hightLightY2, paint);

                        setImageView(bitmapFormResources1.getHeight() + bitmapFormResources.getHeight());
                    }
                })
                .build();
        NewbieGuide.with(getActivity())
                .setLabel("guide")
                .addGuidePage(GuidePage.newInstance()

                        .addHighLightWithOptions(view1, HighLight.Shape.ROUND_RECTANGLE, ScreenUtil.dip2px(getActivity(), 3), -2, options)
                        .setLayoutRes(R.layout.enlighten_page)
                        .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
                            @Override
                            public void onLayoutInflated(View view, Controller controller) {
                                imageView = view.findViewById(R.id.iv_next);
                                imageView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        controller.remove();
                                    }
                                });
                            }
                        })
                        .setEverywhereCancelable(false)

                )
                .alwaysShow(true)
                .show();
    }

    private void setImageView(float bottom) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
        //设置控件的宽高
        //设置各个方向上的间距
        params.setMargins(0, 0, 0, (int) bottom);
        //改变控件的属性
        imageView.setLayoutParams(params);
    }
}
